package tcpMVM;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws Exception {
        System.out.println("------服务端启动------");
        ServerSocket serverSocket = null;
        Socket socket = null;
        DataInputStream dataInputStream = null;
        try {
            //创建ServerSocket对象，同时为服务端注册端口
            serverSocket = new ServerSocket(9999);
            //使用ServerSocket对象，调用accept方法，等到客户端链接
            socket = serverSocket.accept();
            //从端点socket得到一个字节流
            InputStream inputStream = socket.getInputStream();
            //把字节流包装成数据流
            dataInputStream = new DataInputStream(inputStream);
            while (true) {
                //使用数据流读取客户端数据
                String s = dataInputStream.readUTF();
                System.out.println(s);
                System.out.println(socket.getRemoteSocketAddress());
            }
        } catch (Exception ignored) {
            if (socket != null) {
                System.out.println(socket.getRemoteSocketAddress() + "离线了！ ");
            }
            if (dataInputStream != null) {
                dataInputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
        }
    }
}
